package com.hll.servlet;

import com.Constants;
import com.hll.exception.ParameterException;
import com.hll.model.Book;
import com.hll.model.User;
import com.hll.service.BookService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

@WebServlet("/saveBook.action")
public class SaveBookServlet extends HttpServlet {

    private List<String> mockPictures = new ArrayList<>();

    public SaveBookServlet() {
        super();
        mockPictures.add("/static/book/Book1_50x60.png");
        mockPictures.add("/static/book/Book2_50x60.png");
        mockPictures.add("/static/book/Book3_50x60.png");
        mockPictures.add("/static/book/Book4_50x60.png");
        mockPictures.add("/static/book/Book5_50x60.png");
    }

    public static int getRandom() {
        int max = 5;
        int min = 1;
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return s;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String desc = request.getParameter("desc");

        String idStr = request.getParameter("id");
        int id = Integer.parseInt(idStr);

        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(Constants.USER);

        Book book = new Book();
        book.setId(id);
        book.setName(name);
        book.setAuthor(author);
        book.setDesc(desc);
        book.setOwnerId(user.getId());
        book.setCurrentOwnerId(user.getId());
        book.setOwnerName(user.getUserName());
        book.setCurrentOwnerName(user.getUserName());
        book.setPicture(mockPictures.get(getRandom() - 1));
        book.setDeleted(0);

        try {
            BookService bookService = new BookService();
            bookService.save(book);
            session.setAttribute(Constants.SUCCESS_FLASH_MESSAGE, "保存图书成功");
            response.sendRedirect(request.getContextPath() + "/myBook.action");
        } catch (ParameterException parameterException) {
            Map<String, String> errorFields = parameterException.getErrorFields();
            request.setAttribute(Constants.ERROR_FIELDS, errorFields);
            request.setAttribute("book", book);
//            request.getRequestDispatcher(EDIT_BOOK_PAGE).forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

